from sitcpy.rbcp import RbcpBusError, RbcpTimeout, Rbcp, RbcpError
import time
import os

HV_BASE_ADDR = 0x0080_0000


class HV:
    def __init__(self, ip_address="192.168.10.10"):
        self.ip_address = ip_address
        self._rbcp = Rbcp(ip_address)

    def hvset(self, ch, vset):
        self._rbcp.write(HV_BASE_ADDR + ch * 0x1_0000, ("w0102"+vset+"c\r"))
        time.sleep(1)
        value = self._rbcp.read(HV_BASE_ADDR + ch * 0x1_0000, 6)
        print(self.ip_address, "HV", ch, " set to", value)

    def hvread(self, ch):
        self._rbcp.write(HV_BASE_ADDR + ch * 0x1_0000, "r0103c\r")
        time.sleep(0.5)
        value = self._rbcp.read(HV_BASE_ADDR + ch * 0x1_0000, 6)
        print(value)
        #print(self.ip_address.decode(), "HV", ch, "value =", value)
        self._rbcp.write(HV_BASE_ADDR + ch * 0x1_0000, "r010dc\r")
        time.sleep(0.5)
        valuem = self._rbcp.read(HV_BASE_ADDR + ch * 0x1_0000, 6)
        #print(self.ip_address.decode(), "HV", ch, "maxmesvalue =", valuem)
        valuer = round(int(valuem.decode()[1:4],base=16)/4096 * int(value.decode()[1:4],base=16))
        print("HV", ch, "value =", valuer,"V")
        return valuer

    def hvopen(self, ch):
        self._rbcp.write(HV_BASE_ADDR + ch * 0x1_0000, "w01010001c\r")
        time.sleep(1)
        value = self._rbcp.read(HV_BASE_ADDR + ch * 0x1_0000, 6)
        print("HV", ch, "open.")

    def hvclose(self, ch):
        self._rbcp.write(HV_BASE_ADDR + ch * 0x1_0000, "w01010000c\r")
        time.sleep(1)
        value = self._rbcp.read(HV_BASE_ADDR + ch * 0x1_0000, 6)
        print("HV", ch, "closed.")

def hvsetall():
    device_ip = "192.168.10.10"
    # messagebox.showinfo(title='确认', message='请压下把手')
    hv = HV(device_ip)
    hv.hvset(0, "0746"),
    hv.hvset(1, "0746"),
    hv.hvset(2, "0746"),
    print("HVs set")

def hvopenall():
    device_ip = "192.168.10.10"
    hv = HV(device_ip)
    hv.hvopen(0),
    hv.hvopen(1),
    hv.hvopen(2),
    time.sleep(15),
    print("HVs open")

def hvreadall():
    device_ip = "192.168.10.10"
    hv = HV(device_ip)
    value = (
        hv.hvread(0),
        hv.hvread(1),
        hv.hvread(2),
    )
    print("HVs read")
    return value

def hvcloseall():
    device_ip = "192.168.10.10"
    hv = HV(device_ip)
    hv.hvclose(0),
    hv.hvclose(1),
    hv.hvclose(2),
    time.sleep(1),
    print("HVs close")

def main():
    device_ip = "192.168.10.10"
    hv = HV(device_ip)
    hv.hvset(0, "0746"),
    hv.hvset(1, "0746"),
    hv.hvset(2, "0746"),
    print("HVs are set")
    hv.hvopen(0),
    hv.hvopen(1),
    hv.hvopen(2),
    print("HVs are open")
    #while(1):
    #hv.hvread(0),
    #hv.hvread(1),
    #hv.hvread(2),
    #     print("HVs are read")
    #hv.hvclose(0),
    #hv.hvclose(1),
    #hv.hvclose(2),
    # print("HVs are closed")


if __name__ == "__main__":
    main()
